/**
 * Copyright (C) 2024-2030 Super BilGen & 超亿时代信息技术股份有限公司.All Rights Reserved.
 */
package cn.com.yang.threadpool;

import java.util.concurrent.atomic.AtomicInteger;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 * @Model cn.com.yang.threadpool.DefaultThreadFactory
 * @Desc 默认线程工厂（支持自定义线程名前缀）
 * @author yangyijin
 * @since 2025年9月4日-下午7:52:04
 */

public class DefaultThreadFactory implements ThreadFactory {
	private static final Logger logger = LoggerFactory.getLogger(DefaultThreadFactory.class);

    private static final AtomicInteger poolNumber = new AtomicInteger(1);
    private final ThreadGroup group;
    private final AtomicInteger threadNumber = new AtomicInteger(1);
    private final String namePrefix;

    /**
     * 创建线程工厂，使用默认前缀
     */
    public DefaultThreadFactory() {
        this("pool-" + poolNumber.getAndIncrement() + "-thread-");
    }
    
    /**
     * 创建线程工厂，使用自定义前缀
     * @param namePrefix 线程名前缀
     */
    public DefaultThreadFactory(String namePrefix) {
        SecurityManager s = System.getSecurityManager();
        group = (s != null) ? s.getThreadGroup() : Thread.currentThread().getThreadGroup();
        this.namePrefix = namePrefix.endsWith("-") ? namePrefix : namePrefix + "-";
        
        logger.debug("Thread factory created with prefix: {}", this.namePrefix);
    }

    @Override
    public Thread newThread(Runnable r) {
        Thread t = new Thread(group, r, namePrefix + threadNumber.getAndIncrement(), 0);
        if (t.isDaemon()) t.setDaemon(false);
        if (t.getPriority() != Thread.NORM_PRIORITY) t.setPriority(Thread.NORM_PRIORITY);
        
        logger.trace("Created new thread: {}", t.getName());
        return t;
    }
}



